// 引入API模块
const api = require('../../utils/api/index');

Page({
  data: {
    // 主分类（顶部标签页）
    mainCategories: [
      { id: 'breakfast', name: '早餐' },
      { id: 'lunch', name: '午餐' },
      { id: 'dinner', name: '晚餐' },
      { id: 'all', name: '全部' }
    ],
    currentMainCategory: 'all', // 默认显示全部

    // 子分类（横向滚动菜单）
    subCategories: [
      { id: 'all', name: '全部' },
      { id: 'chicken', name: '鸡肉类' },
      { id: 'bean', name: '豆制品类' },
      { id: 'vegetable', name: '蔬菜类' },
      { id: 'grain', name: '粗粮类' },
      { id: 'seafood', name: '海鲜类' },
      { id: 'pork', name: '猪肉类' },
      { id: 'beef', name: '牛肉类' },
      { id: 'fruit', name: '水果类' },
      { id: 'snack', name: '小食类' }
    ],
    currentSubCategory: 'all', // 默认显示全部

    // 搜索相关
    searchQuery: '',
    showSearchResult: false,
    
    // 数据状态
    loading: true,
    recipes: [],
    noData: false,
    
    // 分页加载
    pageSize: 10,
    currentPage: 1,
    hasMoreData: true
  },

  onLoad: function() {
    this.loadRecipes();
  },
  
  onShow: function() {
    // 更新底部TabBar选中状态
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 1 // 饮食页面
      });
    }
  },

  // 切换主分类
  switchMainCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    if (category === this.data.currentMainCategory) return;
    
    this.setData({
      currentMainCategory: category,
      currentPage: 1,
      recipes: [],
      loading: true,
      hasMoreData: true,
      noData: false
    });
    
    this.loadRecipes();
  },
  
  // 切换子分类
  switchSubCategory: function(e) {
    const category = e.currentTarget.dataset.category;
    if (category === this.data.currentSubCategory) return;
    
    this.setData({
      currentSubCategory: category,
      currentPage: 1,
      recipes: [],
      loading: true,
      hasMoreData: true,
      noData: false
    });
    
    this.loadRecipes();
  },
  
  // 搜索框输入
  onSearchInput: function(e) {
    this.setData({
      searchQuery: e.detail.value
    });
  },
  
  // 执行搜索
  doSearch: function() {
    if (!this.data.searchQuery.trim()) {
      // 搜索词为空，恢复正常显示
      this.setData({
        showSearchResult: false,
        currentPage: 1,
        recipes: [],
        loading: true,
        hasMoreData: true,
        noData: false
      });
      this.loadRecipes();
      return;
    }
    
    this.setData({
      showSearchResult: true,
      currentPage: 1,
      recipes: [],
      loading: true,
      hasMoreData: true,
      noData: false
    });
    
    this.searchRecipes();
  },
  
  // 清除搜索
  clearSearch: function() {
    this.setData({
      searchQuery: '',
      showSearchResult: false,
      currentPage: 1,
      recipes: [],
      loading: true,
      hasMoreData: true,
      noData: false
    });
    
    this.loadRecipes();
  },
  
  // 加载食谱数据
  loadRecipes: async function() {
    try {
      const { currentMainCategory, currentSubCategory, pageSize, currentPage } = this.data;
      
      // 显示加载状态
      if (currentPage === 1) {
        this.setData({ loading: true });
      }
      
      // 构建搜索关键词，根据类别生成适当的关键词
      let searchQuery = '';
      
      // 根据子分类添加关键词
      if (currentSubCategory !== 'all') {
        switch(currentSubCategory) {
          case 'chicken': searchQuery = '鸡肉'; break;
          case 'bean': searchQuery = '豆腐'; break;
          case 'vegetable': searchQuery = '蔬菜'; break;
          case 'grain': searchQuery = '粗粮'; break;
          case 'seafood': searchQuery = '海鲜'; break;
          case 'pork': searchQuery = '猪肉'; break;
          case 'beef': searchQuery = '牛肉'; break;
          case 'fruit': searchQuery = '水果'; break;
          case 'snack': searchQuery = '点心'; break;
          default: searchQuery = '';
        }
      }
      
      // 根据主分类添加关键词
      if (currentMainCategory !== 'all') {
        const mealTypeKeywords = {
          'breakfast': '早餐',
          'lunch': '午餐',
          'dinner': '晚餐'
        };
        
        // 如果已有子分类关键词，组合查询
        if (searchQuery) {
          searchQuery += ' ' + mealTypeKeywords[currentMainCategory];
        } else {
          searchQuery = mealTypeKeywords[currentMainCategory];
        }
      }
      
      // 如果没有任何分类筛选，使用默认关键词
      if (!searchQuery) {
        searchQuery = '菜谱';
      }
      
      console.log(`搜索菜谱关键词: "${searchQuery}"`);
      
      // 直接使用天行API搜索菜谱，而不是从本地数据库获取
      const result = await api.diet.searchTianapiRecipes(
        searchQuery,
        pageSize,
        currentPage
      );
      
      if (result && result.success) {
        const newRecipes = result.data || [];
        const allRecipes = currentPage === 1 ? newRecipes : [...this.data.recipes, ...newRecipes];
        
        // 数据处理 - 确保有正确的ID字段
        const processedRecipes = allRecipes.map(recipe => {
          // 如果已有_id字段，使用它作为id
          if (recipe._id && !recipe.id) {
            recipe.id = recipe._id;
          } 
          // 如果没有id字段，生成一个临时ID
          else if (!recipe.id) {
            recipe.id = 'temp_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
          }
          
          // 确保有图片
          if (!recipe.imageUrl) {
            recipe.imageUrl = '/images/recipes/default.jpg';
          }
          
          return recipe;
        });
        
        this.setData({
          recipes: processedRecipes,
          loading: false,
          hasMoreData: newRecipes.length === pageSize,
          noData: processedRecipes.length === 0,
          currentPage: currentPage + 1
        });
      } else {
        this.setData({
          loading: false,
          hasMoreData: false,
          noData: this.data.recipes.length === 0
        });
        
        if (currentPage === 1) {
          wx.showToast({
            title: '未找到相关食谱',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('加载食谱失败:', error);
      
      this.setData({
        loading: false,
        hasMoreData: false,
        noData: this.data.recipes.length === 0
      });
      
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      });
    }
  },
  
  // 搜索食谱
  searchRecipes: async function() {
    try {
      const { searchQuery, pageSize, currentPage } = this.data;
      
      // 显示加载状态
      if (currentPage === 1) {
        this.setData({ loading: true });
      }
      
      // 使用天行API搜索食谱
      const result = await api.diet.searchTianapiRecipes(
        searchQuery,
        pageSize,
        currentPage
      );
      
      if (result && result.success) {
        const newRecipes = result.data || [];
        const allRecipes = currentPage === 1 ? newRecipes : [...this.data.recipes, ...newRecipes];
        
        // 数据处理 - 确保有正确的ID字段
        const processedRecipes = allRecipes.map(recipe => {
          // 如果已有_id字段，使用它作为id
          if (recipe._id && !recipe.id) {
            recipe.id = recipe._id;
          } 
          // 如果没有id字段，生成一个临时ID
          else if (!recipe.id) {
            recipe.id = 'temp_' + Date.now() + '_' + Math.floor(Math.random() * 1000);
          }
          
          // 确保有图片
          if (!recipe.imageUrl) {
            recipe.imageUrl = '/images/recipes/default.jpg';
          }
          
          return recipe;
        });
        
        this.setData({
          recipes: processedRecipes,
          loading: false,
          hasMoreData: newRecipes.length === pageSize,
          noData: processedRecipes.length === 0,
          currentPage: currentPage + 1
        });
      } else {
        this.setData({
          loading: false,
          hasMoreData: false,
          noData: this.data.recipes.length === 0
        });
        
        if (currentPage === 1) {
          wx.showToast({
            title: '未找到相关食谱',
            icon: 'none'
          });
        }
      }
    } catch (error) {
      console.error('搜索食谱失败:', error);
      
      this.setData({
        loading: false,
        hasMoreData: false,
        noData: this.data.recipes.length === 0
      });
      
      wx.showToast({
        title: '搜索失败',
        icon: 'none'
      });
    }
  },
  
  // 到达底部加载更多
  onReachBottom: function() {
    if (this.data.hasMoreData && !this.data.loading) {
      this.setData({ loading: true });
      
      if (this.data.showSearchResult) {
        this.searchRecipes();
      } else {
        this.loadRecipes();
      }
    }
  },
  
  // 下拉刷新
  onPullDownRefresh: function() {
    this.setData({
      currentPage: 1,
      recipes: [],
      loading: true,
      hasMoreData: true,
      noData: false
    });
    
    if (this.data.showSearchResult) {
      this.searchRecipes().then(() => {
        wx.stopPullDownRefresh();
      });
    } else {
      this.loadRecipes().then(() => {
        wx.stopPullDownRefresh();
      });
    }
  },
  
  // 跳转到食谱详情页
  navigateToRecipeDetail: function(e) {
    const recipeId = e.currentTarget.dataset.id;
    if (!recipeId) return;
    
    const recipeIndex = this.data.recipes.findIndex(r => r.id === recipeId);
    if (recipeIndex === -1) return;
    
    // 获取当前食谱对象
    const recipe = this.data.recipes[recipeIndex];
    
    // 如果是API返回的临时食谱（ID以temp_开头），先保存到数据库
    if (recipeId.toString().startsWith('temp_')) {
      wx.showLoading({
        title: '正在保存食谱...',
        mask: true
      });
      
      // 保存食谱到数据库
      api.diet.saveTianapiRecipe(recipe)
        .then(result => {
          wx.hideLoading();
          if (result && result.success) {
            // 获取保存后的ID，跳转到详情页
            const savedId = result.data._id;
            wx.navigateTo({
              url: `../recipeDetail/recipeDetail?id=${savedId}`
            });
          } else {
            throw new Error('保存食谱失败');
          }
        })
        .catch(error => {
          wx.hideLoading();
          console.error('保存食谱失败:', error);
          wx.showToast({
            title: '无法查看详情',
            icon: 'none'
          });
        });
    } else {
      // 正常ID直接跳转
      wx.navigateTo({
        url: `../recipeDetail/recipeDetail?id=${recipeId}`,
        fail: (error) => {
          console.error('跳转到食谱详情页失败:', error);
          wx.showToast({
            title: '页面跳转失败',
            icon: 'none'
          });
        }
      });
    }
  }
}); 